/*
 * VytvoreniUzivatele.java
 *
 * Created on 26.11.2011, 21:26:20
 */
package gui;

import database.DatabazovaChyba;
import java.awt.Component;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import system.Launcher;
import system.RandPass;
import uzivatele.*;

/**
 *
 * @author Jan Lukes
 */
public class VytvoreniUzivatele extends javax.swing.JFrame {

    private RandPass generatorHesel;
    private Uzivatel uzivatel;
    private String email;
    /** Creates new form VytvoreniUzivatele */
    public VytvoreniUzivatele(Uzivatel uzivatel) {
        this.uzivatel = uzivatel;
        generatorHesel = new RandPass();
        initComponents();
        String nazevOkna = "Vytvoření uživatele";
        Launcher.getInstance().setOknoDoprostred(this);
        if (uzivatel != null) {
            nactiUdajeUzivatele();
            email = TextFieldEmail.getText();
            nazevOkna = "Editace uživatele";
        }
        this.setTitle("Správce úkolů - " + nazevOkna
                + " - Přihlášen " + Launcher.getInstance().getUzivatel().getEmail()
                + " - " + UzivatelRank.getNameFromRankId(Launcher.getInstance().getUzivatel().getRank()));

    }

    private void nactiUdajeUzivatele() {
        this.TextFieldName.setText(uzivatel.getJmeno());
        this.TextFieldSurname.setText(uzivatel.getPrijmeni());
        this.TextFieldEmail.setText(uzivatel.getEmail());
        this.TextFieldPassword.setText("********");
        this.TextAreaDescription.setText(uzivatel.getPopis());
        this.ComboBoxRank.setSelectedItem(uzivatel.getRank());
    }

    private void ukazChybu(Component component) {
        component.setBackground(new java.awt.Color(255, 153, 153));
    }

    private void odznacChybu(Component component) {
        component.setBackground(new java.awt.Color(255, 255, 255));
    }

//   public boolean checkMailAddress(String email) {
//        if (email == null || email.equals("")) {
//            return false;
//        }
//        try {
//            InternetAddress emailAddr = new InternetAddress(email);
//            if (hasNameAndDomain(email) == false) {
//                return false;
//            }
//        } catch (AddressException ex) {
//            return false;
//        }
//        return true;
//    }
    /**
     * Vrati true a vsechny formulare zesednou pokud je formular vyplnen spravne, 
     * jinak false a dane pole podbarvi cervene.
     * @return 
     */
    public boolean CheckForm() {
        boolean result = true;
        JTextField[] checkList = {TextFieldEmail, TextFieldPassword,
            TextFieldEmail, TextFieldSurname, TextFieldName};
        for (JTextField c : checkList) {
            if (c.getText().equals("")) {
                ukazChybu(c);
                result = false;
            } else {
                odznacChybu(c);
            }
        }
        if (TextAreaDescription.getText().equals("")) {
            ukazChybu(TextAreaDescription);
            result = false;
        } else {
            odznacChybu(TextAreaDescription);
        }

        return result;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        TextFieldName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        TextFieldSurname = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        TextFieldEmail = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        TextAreaDescription = new javax.swing.JTextArea();
        jLabel5 = new javax.swing.JLabel();
        ComboBoxRank = new javax.swing.JComboBox();
        ButtonSave = new javax.swing.JButton();
        ButtonCancel = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        TextFieldPassword = new javax.swing.JTextField();
        ButtonGeneratePassword = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);

        jLabel1.setText("Jméno:");

        TextFieldName.setToolTipText("zadejte jméno pro nového uživatele");

        jLabel2.setText("Příjmení:");

        TextFieldSurname.setToolTipText("zadejte příjmení pro nového uživatele");

        jLabel3.setText("Email/Login:");

        TextFieldEmail.setToolTipText("zadejte platnou emailovou adresu, tato adresa\n Vám bude sloužit jako přihlašovací jméno");

        jLabel4.setText("Popis:");

        TextAreaDescription.setColumns(20);
        TextAreaDescription.setRows(5);
        TextAreaDescription.setToolTipText("sem patří jakékoliv poznámky ohledně uživatele");
        jScrollPane1.setViewportView(TextAreaDescription);

        jLabel5.setText("Hodnost:");

        if(Launcher.getInstance().getUzivatel().getRank() < 1) {
            ComboBoxRank.setEnabled(false);
        }
        ComboBoxRank.setModel(new javax.swing.DefaultComboBoxModel(uzivatele.UzivatelRank.returnRankArray()));

        ButtonSave.setText("Uložit");
        if(Launcher.getInstance().getUzivatel().getRank() < 2) {
            if(Launcher.getInstance().getUzivatel().getId() != this.uzivatel.getId()) {
                ButtonSave.setEnabled(false);
            }
        }
        ButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonSaveActionPerformed(evt);
            }
        });

        ButtonCancel.setText("Storno");
        ButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonCancelActionPerformed(evt);
            }
        });

        jLabel6.setText("Heslo:");

        TextFieldPassword.setToolTipText("klikněte na tlačítko generovat heslo, nově vygenerované heslo se zobrazí v tomto políčku");

        ButtonGeneratePassword.setText("Generovat heslo");
        ButtonGeneratePassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ButtonGeneratePasswordActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ButtonSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(ButtonCancel))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(ComboBoxRank, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(TextFieldName, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel6))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(TextFieldPassword)
                                    .addComponent(TextFieldSurname, javax.swing.GroupLayout.DEFAULT_SIZE, 104, Short.MAX_VALUE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel3)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(TextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(ButtonGeneratePassword)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TextFieldName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(TextFieldSurname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(TextFieldEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(ComboBoxRank, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(TextFieldPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ButtonGeneratePassword))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(ButtonSave)
                            .addComponent(ButtonCancel)))
                    .addComponent(jLabel4))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void ButtonGeneratePasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonGeneratePasswordActionPerformed
        this.TextFieldPassword.setText(this.generatorHesel.getPass(10));
    }//GEN-LAST:event_ButtonGeneratePasswordActionPerformed

    private void ButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonSaveActionPerformed
        boolean kontrola = CheckForm();
        String heslo = TextFieldPassword.getText().equals("********") ? null : TextFieldPassword.getText();
        if (kontrola) {
            try {
                if (uzivatel != null) {
                    if (TextFieldEmail.getText().equals(email)) {
                        uzivatel.editUser(TextFieldName.getText(), TextFieldSurname.getText(), TextFieldEmail.getText(),
                            TextAreaDescription.getText(), ComboBoxRank.getSelectedIndex(), heslo, 1);
//                        System.out.println(ComboBoxRank.getSelectedIndex());
                    } else if(!Launcher.getInstance().getDatabase().userNameExists(TextFieldEmail.getText())){
                        uzivatel.editUser(TextFieldName.getText(), TextFieldSurname.getText(), TextFieldEmail.getText(),
                            TextAreaDescription.getText(), ComboBoxRank.getSelectedIndex(), heslo, 1);
                    } else {
                        JOptionPane.showMessageDialog(this.getFocusOwner(), "Email již existuje");
                        return;
                    }
                    
                } else {
                    if (Launcher.getInstance().getDatabase().userNameExists(TextFieldEmail.getText())) {
                        JOptionPane.showMessageDialog(this.getFocusOwner(), "Email již existuje");
                        return;
                    }
                    uzivatel = new Uzivatel(-1, "", "", "", "", 0, "");
                    uzivatel.editUser(TextFieldName.getText(), TextFieldSurname.getText(), TextFieldEmail.getText(),
                            TextAreaDescription.getText(), ComboBoxRank.getSelectedIndex(), heslo, 0);
                }
                this.dispose();
            } catch (DatabazovaChyba ex) {
                JOptionPane.showMessageDialog(this.getFocusOwner(), "Chyba pri spojeni s databazi");
            }
        } else {
            JOptionPane.showMessageDialog(this.getFocusOwner(), "Nespravne vyplneny formular");
        }
    }//GEN-LAST:event_ButtonSaveActionPerformed

    private void ButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ButtonCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_ButtonCancelActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton ButtonCancel;
    private javax.swing.JButton ButtonGeneratePassword;
    private javax.swing.JButton ButtonSave;
    private javax.swing.JComboBox ComboBoxRank;
    private javax.swing.JTextArea TextAreaDescription;
    private javax.swing.JTextField TextFieldEmail;
    private javax.swing.JTextField TextFieldName;
    private javax.swing.JTextField TextFieldPassword;
    private javax.swing.JTextField TextFieldSurname;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
